package view;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JFileChooser;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.text.StyleConstants;

import model.Patente;


import control.InFile;



/**
 * MenuDemo
 * @author Adriano de Albuquerque Batista
 * @author Alfeu Buriti
 * @author Pablo Diego Alencar
 * @author Yuri Cariry Cabral de Melo
 *
 */
public class MenuDemo extends JMenuBar {
	private static final long serialVersionUID = 1L;

	private JMenuItem m_copyItem;
	private JMenuItem m_pasteItem;
	public  BuscaPeUI bp;

	// private JPopupMenu m_popup = new JPopupMenu();
	
	
	// BuscaPe====================================== constructor
	public MenuDemo(BuscaPeUI buscape) {
		System.out.println("Inicio do MenuDemo");
		
		BuscaPeUI bp = buscape;
		JMenu fileMenu = new JMenu("File"); // Create new menu

		addMenuItem(fileMenu, "Open...", 'O', "control O", listener);
		addMenuItem(fileMenu, "Export xpdf", 'E', "control E", listener);
		addMenuItem(fileMenu, "Export xml", 'X', "control X", listener);
		addMenuItem(fileMenu, "Import xml", 'I', "control I", listener);
		addMenuItem(fileMenu, "Export database", 'B', "control B", listener);
		addMenuItem(fileMenu, "Save...", 'S', "control S", listener);
		addMenuItem(fileMenu, "Quit", 'Q', "control Q", new QuitAction());
		fileMenu.setMnemonic('F');

		// JMenuItem saveItem = new JMenuItem("Save...");
		// saveItem.setMnemonic('S');
		// saveItem.setAccelerator(KeyStroke.getKeyStroke("control S"));
		// saveItem.addActionListener(listener);

		// (2) Build menubar, menus, and add menuitems.
		// JMenuBar menubar = new JMenuBar(); // Create new menu bar

		// fileMenu.add(saveItem); // Add menu item to the menu
		// fileMenu.addSeparator(); // Add separator line to menu
		// fileMenu.add(quitItem);

		JMenu editMenu = new JMenu("Edit");
		editMenu.setMnemonic('E');

		// (1) Create menu items and set their mnemonic, accelerator, enabled.
		m_copyItem = new JMenuItem("Copy");
		m_copyItem.setEnabled(false);
		m_copyItem.setAccelerator(KeyStroke.getKeyStroke("control C"));

		m_pasteItem = new JMenuItem("Paste");
		m_pasteItem.setEnabled(false);
		m_pasteItem.setAccelerator(KeyStroke.getKeyStroke("control V"));

		editMenu.add(m_copyItem);
		editMenu.add(m_pasteItem);

		JMenu viewMenu = new JMenu("View");
		editMenu.setMnemonic('V');
		// adicionar itens ao menu View
		// aumenta fonte
		addMenuItem(viewMenu, "FONT", 'p', "control A", listener);
		// diminui fonte
		addMenuItem(viewMenu, "font", 'm', "control D", listener);

		JMenu helpMenu = new JMenu("Help");
		helpMenu.setMnemonic('H');
		addMenuItem(helpMenu, "Ler LPI", 'l', "control L", listener);
		addMenuItem(helpMenu, "Ler AN127", 'l', "control N", listener);
		addMenuItem(helpMenu, "Ler desiderata", 'l', "control T", listener);

		bp.historyMenu = new JMenu("History"); 
		bp.historyMenu.setMnemonic('h'); 
		addMenuItem(bp.historyMenu, "Add to history", 'a', "control P",
				listener);

		this.add(fileMenu);
		this.add(editMenu);
		this.add(viewMenu);
		this.add(bp.historyMenu);
		this.add(helpMenu);
		// ... Add the (unused) text area to the content pane.

		// ... Add menu items to popup menu, add popup menu to text area.
		// m_popup.add(new JMenuItem("Testing"));
		// m_editArea.setComponentPopupMenu(m_popup);

		System.out.println("Fim do MenuDemo");
	}

	
	
	/**
	 * addMenuItem -- adds item to pull down menus
	 * 
	 * @param menu
	 * @param item
	 * @param mnemonic
	 * @param keystroke
	 * @param handler
	 */
	public static void addMenuItem(JMenu menu, String item, char mnemonic,
			String keystroke, ActionListener handler) {
		
		System.out.println("Inicio do MenuDemo  -> addMenuItem");
		
		JMenuItem menuItem = new JMenuItem(item);
		menuItem.setMnemonic(mnemonic);
		menuItem.setAccelerator(KeyStroke.getKeyStroke(keystroke));
		menuItem.addActionListener(handler);// Add listeners to menu items
		menu.add(menuItem);
		menu.addSeparator(); // Add separator line to menu
		
		System.out.println("Fim do MenuDemo  -> addMenuItem");		
	}

	
	
	public ActionListener listener = new ActionListener() {		
		// An object that will serve as listener for menu items.
		public void actionPerformed(ActionEvent evt) {
			System.out.println("Inicio do MenuDemo  -> actionPerformed");	
			// This will be called when the user makes a selection
			// from the File menu. This routine just checks
			// which command was selected and calls another
			// routine to carry out the command.
			String cmd = evt.getActionCommand();
			if (cmd.equals(bp.DBItemId)) {
				// Fetch DBItem
				// bp.load(DBItem);
			}
			for (int i = 0; i < bp.pat_list.size(); i++) { 
				if (cmd.equals(bp.pn_list.get(i))) {// tira patente da lista e
					// joga na patente corrente
					bp.patente = bp.pat_list.get(i);
					bp.textPane.sendTextToPane(bp.patente.getAbsTract());
				}
				System.out
						.println("history menu funciona " + bp.pn_list.get(i));
			}
			if (cmd.equals("Open..."))
				doOpen();
			else if (cmd.equals("Save..."))
				doSave();
			else if (cmd.equals("Export pdf"))
				;
			// doPdf();
			else if (cmd.equals("Export xml")) {
				// bp.patente.exportXML(bp.patente);
				// System.out.println("exportando "+bp.patente.patNum+".xml");
				doExportXML();
			} else if (cmd.equals("Import xml")) {
				doImportXML();
			} else if (cmd.equals("FONT")) {
				StyleConstants.setFontSize(bp.textPane.sas, 20);
			} else if (cmd.equals("font")) {
				StyleConstants.setFontSize(bp.textPane.sas, 16);
			} else if (cmd.equals("Add to history")) {
			 	bp.pn_list.add("1"); 
				Patente pat = new Patente(); 
				pat.setDescription(bp.textPane.getText());
				bp.pat_list.add(1, pat);
			} else if (cmd.equals("Quit"))
				System.exit(0); // Terminate the program.

			System.out.println("Fim do MenuDemo  -> actionPerformed");
		}
	};

	
	/**
	 * QuitAction implements ActionListener
	 *
	 */
	class QuitAction implements ActionListener {
		public void actionPerformed(ActionEvent e) {
			System.out.println("Inicio do MenuDemo  -> QuitAction");
			System.exit(0); // Terminate the program.
			System.out.println("Fim do MenuDemo  -> QuitAction");
		}
	}

	/**
	 * doSave 
	 * Carry out the Save command by letting the user specify
	 * an output file and writing the text from the JTextArea
	 * to that file.
	 */
	public void doSave() {
		System.out.println("Inicio do MenuDemo  -> doSave");
	
		File file; // The file that the user wants to save.
		JFileChooser fd; // File dialog that lets the user specify the file.
		fd = new JFileChooser(new File("."));
		fd.setDialogTitle("Save Text As...");
		int action = fd.showSaveDialog(this);
		if (action != JFileChooser.APPROVE_OPTION) {
			// User has canceled, or an error occurred.
			return;
		}
		file = fd.getSelectedFile();
		if (file.exists()) {
			// If file already exists, ask before replacing it.
			action = JOptionPane.showConfirmDialog(this,
					"Replace existing file?");
			if (action != JOptionPane.YES_OPTION)
				return;
		}
		try {
			// Create a PrintWriter for writing to the specified
			// file and write the text from the window to that stream.
			PrintWriter out = new PrintWriter(new FileWriter(file));
			String contents = bp.textPane.getText();
			// tente fazer um arquivo de sa�da com formato xml
			out.print(contents);
			if (out.checkError())
				throw new IOException("Error while writing to file.");
			out.close();
		} catch (IOException e) {
			// Some error has occured while trying to write.
			// Show an error message.
			JOptionPane.showMessageDialog(this,
					"Sorry, an error has occurred:\n" + e.getMessage());
		}

		System.out.println("Fim do MenuDemo  -> doSave");
	}

	
	/**
	 * doOpen
	 */
	public void doOpen() {

		System.out.println("Inicio do MenuDemo  -> doOpen");
		// Carry out the Open command by letting the user specify
		// the file to be opened and reading up to 100 lines from
		// that file. The text from the file replaces the text
		// in the JTextArea.
		File file; // The file that the user wants to open.
		JFileChooser fd; // File dialog that lets the user specify the file.
		fd = new JFileChooser(new File("."));
		fd.setDialogTitle("Open File...");
		int action = fd.showOpenDialog(this);
		if (action != JFileChooser.APPROVE_OPTION) {
			// User canceled the dialog, or an error occurred.
			return;
		}
		file = fd.getSelectedFile();
		try {
			// Read lines from the file until end-of-file is detected,
			// or until 100 lines have been read. The lines are added
			// to the JTextArea, with a line feed after each line.
			// TextReader in = new TextReader(new FileReader(file));
			// BufferedReader bf= new BufferedReader(new InputStreamReader(new
			// FileInputStream(file)));
			String filename = file.getName();
			String text = new InFile().readFile(filename);
			bp.textPane.setText(text);

			// Leia buffer
		} catch (Exception e) {
			// Some error has occured while trying to read the file.
			// Show an error message.
			JOptionPane.showMessageDialog(this, "Sorry, some error occurred:\n"
					+ e.getMessage());
		}

		System.out.println("Fim do MenuDemo  -> doOpen");
	}

	/**
	 * doExportXML
	 * Carry out the Open command by letting the user specify the file to be
	 * opened. O conteudo do arquivo xml de entrada substitui o objeto
	 * bp.patente. in the JTextArea.
	 */
	public void doExportXML() {

		System.out.println("Inicio do MenuDemo  -> doExportXML");

		File file; // The file that the user wants to open.
		JFileChooser fd; // File dialog that lets the user specify the file.
		fd = new JFileChooser(new File("."));
		fd.setDialogTitle("Export XML...");
		int action = fd.showOpenDialog(this);
		if (action != JFileChooser.APPROVE_OPTION) {
			// User canceled the dialog, or an error occurred.
			return;
		}
		File dir = fd.getCurrentDirectory();
		file = fd.getSelectedFile();
		// fd.get
		try {
			// Read lines from the file until end-of-file is detected,
			// or until 100 lines have been read. The lines are added
			// to the JTextArea, with a line feed after each line.
			// TextReader in = new TextReader(new FileReader(file));
			// BufferedReader bf= new BufferedReader(new InputStreamReader(new
			// FileInputStream(file)));
			// String dirname=dir.getName();
			String dirname = dir.getAbsolutePath();
			String filename = file.getName();
			filename = dirname + File.separator + filename;
			bp.patente.exportXML(filename, bp.patente);
			System.out.println("exportando " + filename);

			// Leia buffer
		} catch (Exception e) {
			// Some error has occured while trying to read the file.
			// Show an error message.
			JOptionPane.showMessageDialog(this,
					"Arquivo nao existe, tente novamente:\n" + e.getMessage());
		}

		System.out.println("Fim do MenuDemo  -> doExportXML");
	}

	/**
	 * Carry out the Open command by letting the user specify the file to be
	 * opened. O conteudo do arquivo xml de entrada substitui o objeto
	 * bp.patente. in the JTextArea.
	 */
	public void doImportXML() {

		System.out.println("Inicio do MenuDemo  -> doImportXML");

		File file; // The file that the user wants to open.
		JFileChooser fd; // File dialog that lets the user specify the file.
		fd = new JFileChooser(new File("."));
		fd.setDialogTitle("Import XML...");
		int action = fd.showOpenDialog(this);
		if (action != JFileChooser.APPROVE_OPTION) {
			// User canceled the dialog, or an error occurred.
			return;
		}
		File dir = fd.getCurrentDirectory();
		file = fd.getSelectedFile();
		try {
			// Read lines from the file until end-of-file is detected,
			// or until 100 lines have been read. The lines are added
			// to the JTextArea, with a line feed after each line.
			// TextReader in = new TextReader(new FileReader(file));
			// BufferedReader bf= new BufferedReader(new InputStreamReader(new
			// FileInputStream(file)));
			String dirname = dir.getAbsolutePath();
			String filename = file.getName();
			filename = dirname + File.separator + filename;
			String xml = new InFile().readFile(filename);
			System.out.println("xml import funcionando, lendo " + filename);

			// formato do objeto patente em Patent.java = formato do xml padrao
			// em patent.xml
			bp.patente.setPatNum(bp.patente.getElementByName(xml, "pn"));
			bp.patente.setTitle(bp.patente.getElementByName(xml, "title"));
			bp.patente.setPd(bp.patente.getElementByName(xml, "pd"));
			bp.patente.setInventor(bp.patente.getElementByName(xml, "inventor"));
			bp.patente.setApplicant(bp.patente.getElementByName(xml, "applicant"));
			bp.patente.setIpc(bp.patente.getElementByName(xml, "class"));
			bp.patente.setApplication(bp.patente.getElementByName(xml,
					"application"));
			bp.patente.setPriority(bp.patente.getElementByName(xml, "priority"));
			bp.patente.setFamily(bp.patente.getElementByName(xml, "family"));
			bp.patente.setCited(bp.patente.getElementByName(xml, "cited"));
			bp.patente.setCiting(bp.patente.getElementByName(xml, "citing"));
			bp.patente.setAbsTract(bp.patente.getElementByName(xml, "abstract"));
			bp.patente.setClaims(bp.patente.getElementByName(xml, "claims"));
			bp.patente.setDescription(bp.patente.getElementByName(xml,
					"description"));
			bp.patente.setFigura(bp.patente.getElementByName(xml, "figura"));
			// bp.textPane.setText(bp.patente.claims);
			bp.textPane.sendTextToPane(bp.patente.getDescription());
			
			// Leia buffer
		} catch (Exception e) {
			// Some error has occured while trying to read the file.
			// Show an error message.
			JOptionPane.showMessageDialog(this, "Sorry, some error occurred:\n"
					+ e.getMessage());
		}

		System.out.println("Fim do MenuDemo  -> doImportXML");
	}

}
